﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Net.Mime;

namespace DB
{
	public class AccessDb
	{
        private static readonly AccessDb instance = new AccessDb();
        public static AccessDb Instance
        {
            get
            {
                return instance;
            }
        }
		OdbcConnection connection;
		private string fileName;
		public string FileName
		{
			get { return fileName; }
			set
			{
				string _fileName = value;

				connection = new OdbcConnection();
				if (File.Exists(_fileName))
				{
					connection.ConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=" + _fileName + ";";
					fileName = _fileName;
				}
				else if (File.Exists(value))
				{
					connection.ConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=" + value + ";";
					fileName = value;
				}
				else
				{
					connection.ConnectionString = "";
					fileName = "";
				}

			}
		}

		Dictionary<String, OdbcDataAdapter> dataAdapters = new Dictionary<string, OdbcDataAdapter>();
		DataSet Data = new DataSet();

		public DataTable GetTable(String tableName)
		{
			DataTable res;
			try
			{
				if (dataAdapters.ContainsKey(tableName))
					return Data.Tables[tableName];
				String query = String.Format("select * from {0}", tableName);
				OdbcDataAdapter da = new OdbcDataAdapter(query, connection);
				OdbcCommandBuilder builder = new OdbcCommandBuilder(da);
				da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
				da.Fill(Data, tableName);
				res = Data.Tables[tableName];
				dataAdapters.Add(tableName, da);
			}
			catch
			{
				res = null;
			}
			return res;
		}

		public void OpenConnection()
		{
			if (connection.State == ConnectionState.Open)
				return;
			connection.Open();
		}

		public void CloseConnection()
		{
			connection.Close();
		}
		bool noError;
		public bool Commit()
		{
			noError = true;
			foreach (String table in dataAdapters.Keys)
				try
				{
					dataAdapters[table].RowUpdated += new OdbcRowUpdatedEventHandler(AccesDb_RowUpdated);
					dataAdapters[table].Update(Data, table);
				}
				catch
				{
					noError = false;
				}
			return noError;
		}

		void AccesDb_RowUpdated(object sender, OdbcRowUpdatedEventArgs e)
		{
			if (e.StatementType == StatementType.Delete)
				if (e.Status == UpdateStatus.ErrorsOccurred)
				{
					e.Row.RejectChanges();
					noError = false;
				}
		}

		public bool check()
		{
			return (connection.ConnectionString != "" && connection.ConnectionString != null);
		}
	}
}